package cn.fzc.yipai.service.impl;

import cn.fzc.yipai.entity.LoginResp;
import cn.fzc.yipai.entity.Response;
import cn.fzc.yipai.service.LoginService;
import cn.fzc.yipai.utils.HttpUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.rmi.ServerException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: fu.zc
 * @Date: 2021/7/16 09:12
 * @Description:
 */
@Service
public class LoginServiceImpl implements LoginService {

    public static final String LOGIN_URL = "https://www.yihui-xh.xyz/yip/member/login";
    public static final String YP_URL = "https://www.yihui-xh.xyz/yip/wealth/transferrecord/1/10";

    private final HttpUtils httpUtils;


    @Autowired
    public LoginServiceImpl(HttpUtils httpUtils) {
        this.httpUtils = httpUtils;
    }

    @Override
    public String login(String userName, String pwd) {

        Map<String, String> reqParam = new HashMap<>();
        reqParam.put("login_name", userName);
        reqParam.put("m_pwd", pwd);

        try {
            String result = httpUtils.executePost(LOGIN_URL, null, reqParam);
            if (StringUtils.isNotBlank(result)) {
                Response<LoginResp> response = JSON.parseObject(result, new TypeReference<Response<LoginResp>>() {});
                if (response.getStatus() == 1) {
                    return response.getResult().getToken();
                }
            }
        } catch (ServerException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public boolean checkLogin(String token) {

        String result = httpUtils.executeGet(YP_URL, token);
        if (StringUtils.isNotBlank(result)) {
            Response<Void> response = JSON.parseObject(result, new TypeReference<Response<Void>>() {});
            return response.getStatus() == 1;
        }
        return false;
    }
}
